<?php

namespace app\mfw_comment\controller;

use think\Db;
require_once EXTEND_PATH.'newMfw-sdk/Openapi.php';

class MfwComment
{

    public $count = 1;
    /**
     * 构造函数
     * MfwComment constructor.
     */
    public function __construct(){}

    /**
     *  子进程启动时触发
     * @param $worker
     */
    public function onWorkerStart($worker){
        echo "马蜂窝点评子进程启动了\n";
        if($worker->id === 0 || $worker->id === 1){
            sleep(10);
            \workerman\Lib\Timer::add(30,[$this, 'timeTask']); // 定时器
        }
        if($worker->id === 3){
            sleep(10);
            \workerman\Lib\Timer::add(100,[$this, 'dealComment']); // 定时器
        }
    }

    /**
     * 连接时触发
     * @param $connection
     */
    public function onConnect($connection){
        echo "连接成功\n";
        $connection->send('<h2 style="color: #4288ce;font-size: 20px">hello!</h2>');
    }

    /**
     *  接收到消息时触发
     * @param $connection
     * @param $message
     */
    public function onMessage($connection, $message) {
        var_dump($message);
        $connection->send("<span style='color: #000088;'>很高兴和你认识</span>\n");
    }

    /**
     *  连接关闭时触发
     * @param $connection
     */
    public function onClose($connection){
        echo "连接断开了\n";
    }

    /**
     *  worker进程停止时触发
     * @param $connection
     */
    public function onWorkerStop($connection){
        echo "正在重启!\n";
    }


    /**
     *  从马蜂窝平台获取点评信息
     */
    public function timeTask($page_no = 1)
    {
        echo "定时任务ccc\n";
        $action = 'sales.order.comment.list.get';
        $data = [];
        $data['page_no'] = $page_no; // 默认为1,1页只查询20条数据
        $mfwObj = new \MSDK_Php_Openapi();
        if (false == $mfwObj->send($action, $data)){
            $msg['status'] = false;
            $msg['error_id'] = 1905051424;
            $msg['msg'] = '接口调用失败';
            $msg['get_msg'] = $mfwObj->getError();
            $msg['get_error'] = $mfwObj->getErrno();
            $mfwLog = 'mfw_comment_list_error';
            logs($mfwLog, date('Y-m-d H:i:s', time()));
            logs($mfwLog, $msg);
        }else{
            $getMfwCommentData = $mfwObj->getData();
            $saveData = []; // 保存数据
            // logs('getMfwCommentData', $getMfwCommentData);
            $total = $getMfwCommentData['total']; // 根据条件获取的总条数
            $result = $getMfwCommentData['list']; // 根据添加获取的其中20条数据
            // 保存数据
            if (!empty($result)){
                foreach ($result as $index => $item) {
                    $itemId = $item['id']; // 马蜂窝点评id
                    $saveData[$index]['mfw_comment_id'] = $itemId;
                    $saveData[$index]['order_id'] = $item['order_id'];
                    $saveData[$index]['uid'] = $item['uid'];
                    $saveData[$index]['username'] = $item['username'];
                    $saveData[$index]['user_phone'] = $item['user_phone'];
                    $saveData[$index]['ctime'] = empty($item['ctime'])?'':strtotime($item['ctime']);
                    $saveData[$index]['mtime'] = empty($item['mtime'])?'':strtotime($item['mtime']);
                    $saveData[$index]['star'] = $item['star'];
                    $subStar = empty($item['sub_star']) ? '':$item['sub_star'];
                    if (!empty($subStar)){
                        $subStr = '';
                        foreach ($subStar as $index01 => $item02) {
                            $subStr .= implode('-',$item02).',';
                        }
                        $subStar = rtrim($subStr,',');
                    }
                    $saveData[$index]['sub_star'] = $subStar;
                    $startTags = '';
                    if (!empty($item['star_tags'])){
                        foreach ($item['star_tags'] as $index03 => $item03) {
                            $startTags .= $item03['name'].',';
                        }
                        $startTags = rtrim($startTags, ',');
                    }
                    $saveData[$index]['star_tags'] = $startTags;
                    $saveData[$index]['content'] = $item['content'];
                    $saveData[$index]['reply'] = $item['reply'];
                    $saveData[$index]['sales_id'] = $item['sales_id'];
                    $saveData[$index]['img_count'] = $item['img_count'];
                    $imageInfo = '';
                    if (!empty($item['img_count'])){
                        foreach ($item['image_info'] as $index04 => $item04) {
                            $imageInfo .= $item04['img_src'].',';
                        }
                    }
                    $saveData[$index]['image_info'] = rtrim($imageInfo,',');
                    $saveData[$index]['is_deal'] = 0;
                    $find = Db::name('mfw_comment')->where('order_id',$item['order_id'])
                                                            ->find();
                    if ($find){
                        Db::name('mfw_comment')->where('order_id',$item['order_id'])
                            ->strict(false)->update($saveData[$index]);
                        unset($saveData[$index]);
                    }else{
                        // 处理订单评论
//                        logs('syncMfwComment',$saveData[$index]);
                        self::syncMfwComment($saveData[$index]);
                    }
                }
            }
            if(!empty($saveData)){
                Db::name('mfw_comment')->strict(false)->insertAll($saveData);
            }
        }
    }

    /**
     * 把马蜂窝点评内容存放到订单评论表中,并更改订单为好评
     * @param array $data
     */
    public static function syncMfwComment($data = [])
    {
        if (!empty($data)){
            $saveData = []; // 保存数据
            $saveData['oid'] = $data['order_id'];
            $saveData['platform'] = 'mfw';
            $saveData['uid'] = $data['uid'];
            $saveData['user_name'] = $data['username'];
            $saveData['comment'] = $data['content'];
            $saveData['shop_name'] = '花儿户外';
            $saveData['reply'] = $data['reply'];
            $saveData['comment_status'] = ($data['star'] == 5) ? 1:2;
            $saveData['img_src'] = $data['image_info'];
            $saveData['create_time'] = $data['ctime'];
            $find = Db::name('order_evaluate')->where('oid',$data['order_id'])->find();
            if ($find){
                Db::name('order_evaluate')->where('oid',$data['order_id'])
                                            ->strict(false)->update($saveData);
            }else{
                Db::name('order_evaluate')->strict(false)->insert($saveData);
                // 更改订单评价
                self::changeOrderEvaluateStatus($data['order_id']);
            }
        }else{ // 每次处理200条
            $result = Db::name('mfw_comment')->where('is_deal','<>',1)
                                        ->limit(100)->select();
            if ($result){
                $saveData = []; // 保存数据
                $commentIds= '';
                foreach ($result as $index => $item) {
                    $find = Db::name('order_evaluate')->where('oid',$item['order_id'])->find();
                    if ($find){
                        Db::name('mfw_comment')->where('order_id',$item['order_id'])
                            ->update(['is_deal'=>1]);
                        Db::name('order_evaluate')->where('oid',$item['order_id'])
                                                        ->update(['comment_id'=>$item['id']]);
                        self::changeOrderEvaluateStatus($item['order_id']);
                        continue;
                    }
                    $saveData[$index]['oid'] = $item['order_id'];
                    $saveData[$index]['platform'] = 'mfw';
                    $saveData[$index]['uid'] = $item['uid'];
                    $saveData[$index]['user_name'] = $item['username'];
                    $saveData[$index]['comment'] = $item['content'];
                    $saveData[$index]['shop_name'] = '花儿户外';
                    $saveData[$index]['reply'] = $item['reply'];
                    $saveData[$index]['comment_status'] = ($item['star'] == 5) ? 1:2;
                    $saveData[$index]['img_src'] = $item['image_info'];
                    $saveData[$index]['create_time'] = $item['ctime'];
                    $commentIds .= $item['id'].',';
                }
                if (!empty($saveData)){
                    $commentIds = rtrim($commentIds,','); // 马蜂窝评论表的id
                    Db::name('order_evaluate')->strict(false)->insertAll($saveData);
                    sleep(10);
                    self::changeOrderEvaluateStatus($commentIds, 2);
                }
            }
        }
    }

    /**
     *  更改订单评价状态
     *  如果有评论将订单默认为好评
     */
    public static function changeOrderEvaluateStatus($orderId = '', $code = 0)
    {
        if (!empty($orderId) && empty($code)){
            Db::name('order')
                ->where('order_id',$orderId)
                ->where('order_status','issue')
                ->where('dispose_status','normal_travel')
                ->update(['is_review'=>1]);
        }elseif($code == 2){
            // 处理
            $ret = Db::name('mfw_comment')->where('id','in',$orderId)->select();
            if ($ret){
                foreach ($ret as $index => $item) {
                    Db::name('order')
                        ->where('order_id',$item['order_id'])
                        ->where('order_status','issue')
                        ->where('dispose_status','normal_travel')
                        ->update(['is_review'=>1]);
                }
            }
        }
    }

    /**
     *  处理评论
     */
    public function dealComment()
    {
        echo "第三进程\n";
        self::syncMfwComment();
    }
}